﻿using System;
using System.Collections.Generic;
using System.Linq;
using PetaPoco;

namespace PushTask
{
    public class MessageDeviceBLL
    {
        public static void SendFail_MessageIds(IEnumerable<int> messageIds)
        {
            var list = messageIds.ToList();
            list.Add(-1);
            Database db = new Database();
            db.Execute("update messagedevice set failsendcount=failsendcount+1,nextsendtime=addtime(now(),'00:05:00') where messageid in (@0)", list.ToArray());
        }
        public static void SendFail_Ids(IEnumerable<int> ids)
        {
            var list = ids.ToList();
            list.Add(-1);
            Database db = new Database();
            db.Execute("update messagedevice set failsendcount=failsendcount+1,nextsendtime=addtime(now(),'00:05:00') where id in (@0)", list.ToArray());
        }

        public static void SendSuccess_Ids(IEnumerable<int> ids)
        {
            var list = ids.ToList();
            list.Add(-1);
            Database db = new Database();
            db.Execute("update messagedevice set sendresult=1 where id in (@0)", list.ToArray());
        }

        public static void SendFail(int messageId, string deviceStr, string message)
        {
            Database db = new Database();
            db.Execute("update messagedevice set failsendcount=failsendcount+1,exception=@0,nextsendtime=addtime(now(),'00:05:00') where messageid=@1 and devicestr=@2", message, messageId, deviceStr);
        }
        public static void SendSuccess(int messageId, string deviceStr)
        {
            Database db = new Database();
            db.Execute("delete from messagedevice where messageid=@0 and devicestr=@1", messageId, deviceStr);
        }

        public static DeviceData GetFirstDevice(int messageId, int devicetype, bool isUseGoogle)
        {
            Database db = new Database();
            return db.FirstOrDefault<DeviceData>("select Id,DeviceStr from messagedevice where messageid=@0 and devicetype=@1 and isusegoogle=@2 order by id limit 1", messageId, devicetype, isUseGoogle);
        }

        public static int GetDeviceCount(int messageId, int devicetype, bool isUseGoogle)
        {
            Database db = new Database();
            var count = db.ExecuteScalar<int>("select count(1) from messagedevice where messageId=@0 and devicetype=@1 and isusegoogle=@2 and devicestr is not null", messageId, devicetype, isUseGoogle);
            return count;
        }

        public static List<DeviceData> GetDevices(int startId, int messageId, int devicetype, bool isUseGoogle, int size)
        {
            Database db = new Database();
            return db.Fetch<DeviceData>("select Id,DeviceStr from messagedevice where id>=@0 and messageId=@1 and devicetype=@2 and isusegoogle=@3 and devicestr is not null limit @4", startId, messageId, devicetype, isUseGoogle, size);
        }

    }
}
